package com.mk.es.service.transport.handler;

import com.alibaba.fastjson.JSON;

import com.mk.es.service.transport.entity.EsItem;
import com.mk.es.service.transport.entity.EsQueryResult;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;

import java.util.ArrayList;

/**
 * 处理ES查询结果 适配器
 * @param <T>
 */
public abstract class AbstractEsSearchResponseHandlerAdapter<T> implements EsSearchResponseHandler<T> {

    /**
     * 处理ES查询结果
     * @param response
     * @param clazz
     * @return
     * @throws IllegalAccessException
     * @throws InstantiationException
     */
    @Override
    public EsQueryResult<T> handle(SearchResponse response, Class<T> clazz) throws IllegalAccessException, InstantiationException {
        EsQueryResult<T> queryResult = new EsQueryResult<T>();

        //hits
        SearchHits searchHits = response.getHits();
        queryResult.setTotalRecord(searchHits.getTotalHits()); //总记录数

        //查询结果项
        ArrayList<EsItem<T>> esItems = new ArrayList<>();
        SearchHit[] searchHitArr = searchHits.getHits(); //获取搜索结果
        for (SearchHit searchHitObj : searchHitArr) {
            if (searchHitObj == null) {
                continue;
            }
            if (!searchHitObj.hasSource()) {
                continue;
            }

            String sourceAsString = searchHitObj.getSourceAsString();
            if (StringUtils.isBlank(sourceAsString)) {
                continue;
            }

            //解析成对应的对象
            T obj = JSON.parseObject(searchHitObj.getSourceAsString(), clazz);
            esItems.add(new EsItem<T>(obj));
        }

        if (!esItems.isEmpty()) {
            queryResult.setItems(esItems);
        }
        return queryResult;
    }

}
